<template>
  <div class="box">
    <ul>
      <li>
        <div class="left">
          <img src="img/bitian@2x.png" alt=""><span>发起人</span>
        </div>
        <div class="right">
          {{name}}
        </div>
      </li>
      <li @click="selectPart">
        <div class="left">
          <img src="img/bitian@2x.png" alt=""><span>备课组</span>
        </div>
        <div class="right rights">
          {{group}}
          <van-icon name="arrow" />
        </div>
      </li>
      <li>
        <div class="left">
          <img src="img/bitian@2x.png" alt=""><span>课程环节</span>
        </div>
        <div class="right">
          {{title}}
        </div>
      </li>
    </ul>
    <!-- 上传文件 -->
    <div class="upload">
      <div class="title"><img src="img/bitian@2x.png" alt=""><span>上传文件</span></div>
      <div class="video">
        <van-uploader ref="file" v-model="fileList" accept="video/*" :max-size="400000 * 1024" @oversize="onOversize" :max-count="1" :after-read="afterRead" />
      </div>
    </div>
    <!-- 确定 -->
    <van-button class="button" @click="submit" :loading="loading" :disabled="loading" loading-text="上传中,请勿离开页面" type="info">确定</van-button>

    <!-- <button @click="submit">确定</button> -->
    <van-popup v-model="show" position="bottom">
      <van-picker title="选择备课组" show-toolbar :columns="columns" @confirm="onConfirm" @cancel="onCancel" @change="onChange" />
    </van-popup>
    <!-- 进度条 -->
    <div class="progress">
      <van-progress :percentage="percentage" :show-pivot="false" />
    </div>
  </div>
</template>
<script>
const qiniu = require("qiniu-js");
export default {
  mounted() {
    this.title = this.$route.query.title;
    this.queryToken();
    (async () => {
      let { data } = await this.get("/approve/selectGroupByUserId", {
        userId: localStorage.getItem("id"),
      });
      this.list = data;
      this.columns = data.map((item) => {
        return {
          id: item.groupId,
          text: item.groupName,
        };
      });
      let message = await this.get("/user/userInfoShow", {
        userId: localStorage.getItem("id"),
      });
      this.name = message.data.userName;
      console.log(data);
    })();
  },
  data() {
    return {
      subscription:'',
      // 进度条显示
      // progressFlag: false,
      percentage: 0,
      fileList: [],
      show: false,
      name: "",
      loading: false,
      groupBoss: "",
      groupBossuser: "",
      groupId: "",
      title: "",
      list: [],
      fileTime: "",
      group: "请选择备课组",
      columns: ["杭州", "宁波", "温州", "绍兴", "湖州", "嘉兴", "金华", "衢州"],
      token: "",
    };
  },
   destroyed() {
      console.log(111);
      if(this.subscription){
        
        this.subscription.unsubscribe()
      }
      
    },
  methods: {
    // 请求上传视频token
    queryToken() {
      (async () => {
        const res = await this.get("/approve/tokenResult");
        this.token = res.msg;
      })();
    },
    onOversize(file) {
      console.log(file);
      this.Toast("文件大小不能超过 400Mb");
    },
    afterRead(file) {
      // console.log(this.fileList);
      let videoUrl = URL.createObjectURL(file.file);
      let audioElement = new Audio(videoUrl);
      audioElement.addEventListener("loadedmetadata", () => {
        let duration = audioElement.duration;
        this.fileTime = parseInt(duration);
      });
      // this.$toast.success(this.$refs.file.duration);
      console.log(this.$refs.file);
    },
    selectPart() {
      this.show = true;
    },
    onConfirm(value, index) {
      this.group = value.text;
      this.groupId = value.id;
      (async () => {
        let { data } = await this.get("/approve/selectGroupBossByGroupId", {
          groupId: value.id,
        });
        console.log(data);
        if (data == null) {
          this.$toast.fail({
            message: "无备课组组长,请联系管理员",
            duration: 2500,
          });
          this.$router.back();
        } else {
          this.groupBoss = data.id;
          this.groupBossuser = data.userName;
        }
      })();
      this.show = false;
    },
    onChange(picker, value, index) {},
    onCancel() {
      this.show = false;
    },
   
    submit() {
      var that = this;
      
      if (this.group == "请选择备课组") {
        this.Toast("请选择备课组");
        return;
      }
      if (!this.fileList.length) {
        this.Toast("请上传视频");
        return;
      }
      that.loading = true;
      let formData = new FormData();

      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2,
      };
      const putExtra = {
        fname: "qiniu.txt",
        mimeType: "video/mp4",
        customVars: { "x:test": "qiniu" },
        metadata: { "x-qn-meta-": "qiniu" },
      };
      const observer = {
        next(res) {
          that.percentage = res.total.percent;
          if (res.total.percent == 100) {
            // 此时调用后台的接口
            // formData.append("file", this.fileList[0].file);
            formData.append(
              "key",
              "/app2/" +
                that.fileList[0].file.lastModified +
                that.fileList[0].file.name
            );
            formData.append("fileName", that.fileList[0].file.name);
            formData.append("fileTime", that.fileTime);
            formData.append("classpartId", that.$route.query.partId);
            formData.append("classId", that.$route.query.lessonId);
            formData.append("groupBoss", that.groupBoss);
            formData.append("groupBossuser", that.groupBossuser);
            formData.append("submituserId", localStorage.getItem("id"));
            formData.append("submituserName", that.name);
            formData.append("groupId", that.groupId);
            that.loading = true;
            (async () => {
              let data = await that.post("/approve/addJingCaiVideo", formData);
              if (data.code == 200) {
                that.Toast({
                  message: "提交成功，等待审批",
                  duration: 1000,
                  onClose: () => {
                    that.loading = false;
                    that.$router.back();
                  },
                });
              }
            })();
          }
        },
        error(err) {
          // ...
        },
        complete(res) {
          // ...
        },
      };
      const observable = qiniu.upload(
        // 文件本身
        this.fileList[0].file,
        "/app2/" +
          this.fileList[0].file.lastModified +
          this.fileList[0].file.name,
        this.token,
        putExtra,
        config
      );
      this.subscription = observable.subscribe(observer);
    },
  },
};
</script>
<style lang="scss" scoped>
.box {
  background: #f7f9fa;
  height: 100%;
  position: relative;
  .progress {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
}
ul {
  li {
    background: white;
    padding: 0.3rem 0.24rem;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    color: #606060;
    font-size: 0.3rem;
    border-top: 0.02rem solid #f7f9fa;
    justify-content: space-between;
    .rights {
      display: flex;
      align-items: center;
    }
    .left {
      display: flex;
      align-items: center;
      color: #7e7e7e;
      width: 2rem;
      img {
        width: 0.12rem;
        height: 0.14rem;
      }
      span {
        margin-left: 0.1rem;
      }
    }
  }
}
.upload {
  padding: 0.3rem 0.24rem;
  background: white;
  box-sizing: border-box;
  font-size: 0.3rem;
  margin-top: 0.2rem;
  .video {
    margin-top: 0.3rem;
  }
  .title {
    display: flex;
    align-items: center;
    color: #7e7e7e;
    img {
      width: 0.12rem;
      height: 0.14rem;
    }
    span {
      margin-left: 0.1rem;
    }
  }
}
.button {
  width: 7.02rem;
  height: 0.84rem;
  background: #2e9eff;
  border: 0.01rem solid #2e9eff;
  box-shadow: 0.01rem 0.12rem 0.12rem 0.02rem rgba(4, 111, 204, 0.07);
  border-radius: 0.08rem;
  position: fixed;
  bottom: 0.24rem;
  left: 50%;
  transform: translateX(-50%);
  font-size: 0.33rem;
  line-height: 0.84rem;
  text-align: center;
  font-family: PingFang SC;
  font-weight: bold;
  color: #ffffff;
}
</style>